package cn.sh.library.gmwx.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import cn.sh.library.gmwx.common.ModelManager;


/**
 *
 * @auth liuyi
 * @date 2015-3-9
 */
@Component
public class ContextInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        request.setAttribute("ctx", request.getContextPath());
        ModelManager.closeAll();
        if(handler instanceof HandlerMethod){
            if(modelAndView != null) {
                HandlerMethod method = (HandlerMethod)handler;
                String packageName = method.getBean().getClass().getPackage().getName();
                String prefix = packageName.substring(packageName.lastIndexOf(".") + 1);
                if(StringUtils.isNotEmpty(modelAndView.getViewName()) && modelAndView.getViewName().indexOf(":")!=-1){
                    return;
                }
                if(ArrayUtils.contains(new String[]{"normal", "admin"}, prefix)){
                    modelAndView.setViewName(prefix + "/" + modelAndView.getViewName());
                }
            }
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
